<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多人聊天室</title>
    <style>
        ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .msg-list {
            position: relative;
            width: 600px;
            margin: 0 auto;
        }

        .msg-list ul {
            padding: 10px;
            min-height: 200px;
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
        }

        .msg-list li {
            float: left;
            clear: both;
            margin: 10px 0;
            padding: 5px;
            line-height: 2;
            border-radius: 5px;
            background-color: #efefef;
        }

        .msg-list li h4 {
            margin: 0;
            margin-bottom: 10px
        }

        .msg-list li.active {
            float: right;
            background-color: #58bc58;
            color: #fff;
        }

        .msg-list textarea {
            display: block;
            min-height: 50px;
            margin: 10px 0;
            width: 100%;
            box-sizing: border-box;
        }

        .status {
            display: none;
            position: absolute;
            left: 50px;
            bottom: 0;
            right: 0;
            padding: 5px 10px;
            text-align: center;
            color: #999;
        }

        .login {
            text-align: right;
        }
    </style>
</head>

<body>
    <h1>多人聊天室</h1>
    <div id="autoAnswer" class="msg-list">
        <div class="login"><input type="text" name="username" id="username"><button class="btn-login">进入</button><button
                class="btn-logout">退出</a></div>
        <ul>
            <!-- <li>约吗</li>
            <li class="active">滚</li> -->
        </ul>
        <textarea></textarea>
        <button class="btn-send">提交</button>
        <div class="status"></div>
    </div>
</body>
<script>
    (() => {
        /**
			 * 客户端Socket
			    * HTML5新特性：WebSocket
            
                前后端协商数据格式:{data,status}
                
				
			 */
        let autoAnswer = document.querySelector('#autoAnswer');
        let login = autoAnswer.querySelector('.login');
        let username = login.children[0];
        let btnLogin = login.children[1];//进入聊天室按钮
        let btnLogout = login.children[2];//退出聊天室按钮

        let msglist = autoAnswer.querySelector('ul');
        let msg = autoAnswer.querySelector('textarea');
        let btnSend = autoAnswer.querySelector('.btn-send');
        let status = autoAnswer.querySelector('.status');

        let socket = null;
        let charList = [];//准备一个数组用于存储聊天数据

        function data(type, username, content, time) {
            /*
                type：类型  0:退出登录 1:登录成功 2:发送消息
                username ：用户名
                content : '聊天内容'
                time : 时间
            */
            let status = {
                type,
                username,
                content,
                time
            }
            return JSON.stringify(status);
        }

        function creatList() {
            //创建列表
            let str = charList.map(item => {
                return `<li ${item.username === username.value ? 'class="active"' : ''}>
                                <h4>${item.username}：</h4>
                                <div>${item.content}</div>
                                <time>${new Date(item.time).toLocaleString()}</time>
                        </li>`
            }).join('');
            msglist.innerHTML = str;
        }

        //点击进入聊天室就开始建立ws连接
        btnLogin.onclick = function() {
            let val = username.value;
            if(val.trim()) {
                socket = new WebSocket('ws://localhost:2020');
            }

            //监听：如果连接成功就会触发这个方法
            socket.onopen = function () {
                username.disabled = true;
                let str = data(1, username.value, '我来了', '');
                socket.send(str);//发送消息给服务器 ：客户端给服务器端发消息
            }

            //监听：如果服务器有发消息过来，就跨域监听到
            socket.onmessage = function(ev) {
                console.log(ev.data)
                let data = JSON.parse(ev.data);

                if(data.type == 1) {
                    //登录成功
                    status.style.display = 'block';
                    status.innerHTML = data.username + '上线啦';
                    setTimeout(()=> {//3秒后提示框消失
                        status.style.display = 'none';
                    },3000);
                }

                if(data.type == 2) {
                    //聊天消息处理
                    charList.push(data);//[{},{}]
                    creatList();//渲染页面
                }

                if(data.type == 0) {
                    status.style.display = 'block';
                    status.innerHTML = data.username + '下线了';
                    setTimeout(()=> {//3秒后提示框消失
                        status.style.display = 'none';
                    },3000);
                }

            }

            //监听：如果退出了
            socket.onclose = function () {
                username.disabled = false;
                
            }

        }
        

        btnSend.onclick = () => {
            let val = msg.value;
            if(val.trim()) {//去除前后空格
                //数据不为空，就发给服务器
                let str = data(2, username.value, msg.value,new Date());
                socket.send(str);
            }
        }
        

        //点击退出的时候退出聊天室
        btnLogout.onclick = function () {
            console.log('退出');
            let str = data(0, username.value, '我走啦', '');
            socket.send(str);
            username.value = '';
            socket.close();//关闭

        }
    })();
</script>

</html>